package softwaredepartment.zxit.com.pt_3280cinandroid;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class CallOtherActivity extends AppCompatActivity {

    private TextView tv_tip_info;
    private String AimIPAddress = "";
    private String FLAG_STATE = "4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_other);
        initData();
        initView();
        tv_tip_info.setText("正在连接" + AimIPAddress + "中...");
        Thread callOthersThread = new Thread(new CallOthersThread());
        callOthersThread.start();
        timeVoid();
    }


    private void initView() {
        tv_tip_info = (TextView) findViewById(R.id.tv_tip_info);
    }

    private void initData() {

        Intent intent = getIntent();
        //从Intent当中根据key取得value
        AimIPAddress = intent.getStringExtra("AimIPAddress");
    }

    public class CallOthersThread implements Runnable {

        @Override
        public void run() {
            while (FLAG_STATE.equals("4")) {
                try {
                    Socket s = new Socket(AimIPAddress, 30000);
                    s.setSoTimeout(15000);
                    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    PrintStream ps = new PrintStream(s.getOutputStream());
                    ps.print(AimIPAddress);
                    String json = br.readLine();
                    if(json!=null){
                        /*'result':{'code':'001',info:'正忙！请稍后再试。'}*/
                        JSONObject result = new JSONObject(json);
                        String code = result.getString("code");
                        if(code.equals("002")){
                            //启动两个线程录音线程和收听线程
                            FLAG_STATE = "2";
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public void timeVoid() {
        final Timer timer = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                if (FLAG_STATE.equals("4")) {
                    FLAG_STATE = "0";
                    setResult(100);
                    finish();
                }
                timer.cancel();
            }
        };
        timer.schedule(tt, 15000);
    }
}
